package com.shuaigef.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuaigef.springbootinit.common.Result;
import com.shuaigef.springbootinit.mapper.*;
import com.shuaigef.springbootinit.model.dto.req.post.*;
import com.shuaigef.springbootinit.model.dto.resp.post.GetPostByIdRespDTO;
import com.shuaigef.springbootinit.model.dto.resp.post.GetPostListRespDTO;
import com.shuaigef.springbootinit.model.dto.resp.post.GetPostSayBySayIdRespDTO;
import com.shuaigef.springbootinit.model.entity.*;
import com.shuaigef.springbootinit.service.PostService;
import com.shuaigef.springbootinit.utils.LoginUserContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 帖子服务实现类
 */
@Service
@RequiredArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    private final PostMapper postMapper;
    private final PostLikeMapper postLikeMapper;
    private final PostSayMapper postSayMapper;
    private final SayLikeMapper sayLikeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addPost(AddPostReqDTO requestParam) {
        // 创建帖子
        Post post = new Post();
        post.setPostTitle(requestParam.getPostTitle());
        post.setPostMsg(requestParam.getPostMsg());
        post.setPostModel(requestParam.getPostModel());
        post.setUserId(LoginUserContextHolder.getUserId());
        post.setPostTime(LocalDateTime.now());
        post.setPostSupport(0);
        post.setPostStatus(0);
        post.setPostSay("0");
        
        // TODO: 处理图片上传，设置imgUrl
        
        save(post);
        return Result.success();
    }

    @Override
    public Result<GetPostByIdRespDTO> getPostById(Integer id) {
        Post post = getById(id);
        if (post == null) {
            return Result.error(404, "帖子不存在");
        }

        GetPostByIdRespDTO respDTO = new GetPostByIdRespDTO();
        BeanUtils.copyProperties(post, respDTO);

        // 检查当前用户是否点赞
        Integer userId = LoginUserContextHolder.getUserId();
        LambdaQueryWrapper<PostLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostLike::getPostId, id)
                .eq(PostLike::getUserId, userId);
        respDTO.setIsLike(postLikeMapper.selectCount(wrapper) > 0);

        return Result.success(respDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> likePost(LikePostReqDTO requestParam) {
        Integer userId = LoginUserContextHolder.getUserId();
        
        // 检查是否已点赞
        LambdaQueryWrapper<PostLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostLike::getPostId, requestParam.getPostId())
                .eq(PostLike::getUserId, userId);
        if (postLikeMapper.selectCount(wrapper) > 0) {
            return Result.error(400, "已经点赞过了");
        }

        // 添加点赞记录
        PostLike postLike = new PostLike();
        postLike.setPostId(requestParam.getPostId());
        postLike.setUserId(userId);
        postLike.setLikeTime(LocalDateTime.now());
        postLikeMapper.insert(postLike);

        // 更新帖子点赞数
        Post post = getById(requestParam.getPostId());
        post.setPostSupport(post.getPostSupport() + 1);
        updateById(post);

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> addSay(AddPostSayReqDTO requestParam) {
        PostSay postSay = new PostSay();
        postSay.setPostId(requestParam.getPostId());
        postSay.setUserId(LoginUserContextHolder.getUserId());
        postSay.setParentId(requestParam.getParentId());
        postSay.setSayContent(requestParam.getSayContent());
        postSay.setSayTime(LocalDateTime.now());
        postSay.setSaySupport(0);
        postSayMapper.insert(postSay);

        // 更新帖子评论数
        Post post = getById(requestParam.getPostId());
        int commentCount = Integer.parseInt(post.getPostSay());
        post.setPostSay(String.valueOf(commentCount + 1));
        updateById(post);

        return Result.success();
    }

    @Override
    public List<GetPostSayBySayIdRespDTO> getSays(Integer postId, GetPostSayReqDTO requestParam) {
        LambdaQueryWrapper<PostSay> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostSay::getPostId, postId);
        if (requestParam.getSayId() != null) {
            wrapper.eq(PostSay::getParentId, requestParam.getSayId());
        } else {
            wrapper.isNull(PostSay::getParentId);
        }
        wrapper.orderByDesc(PostSay::getSayTime);

        List<PostSay> postSays = postSayMapper.selectList(wrapper);
        Integer userId = LoginUserContextHolder.getUserId();

        return postSays.stream().map(say -> {
            GetPostSayBySayIdRespDTO respDTO = new GetPostSayBySayIdRespDTO();
            BeanUtils.copyProperties(say, respDTO);

            // 检查是否点赞
            LambdaQueryWrapper<SayLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(SayLike::getSayId, say.getSayId())
                    .eq(SayLike::getUserId, userId);
            respDTO.setIsLike(sayLikeMapper.selectCount(likeWrapper) > 0);

            return respDTO;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updatePost(UpdatePostByIdReqDTO requestParam) {
        Post post = getById(requestParam.getPostId());
        if (post == null) {
            return Result.error(404, "帖子不存在");
        }

        if (!post.getUserId().equals(LoginUserContextHolder.getUserId())) {
            return Result.error(403, "无权修改他人的帖子");
        }

        post.setPostTitle(requestParam.getPostTitle());
        post.setPostMsg(requestParam.getPostMsg());
        post.setPostModel(requestParam.getPostModel());
        
        // TODO: 处理图片更新，更新imgUrl

        updateById(post);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deletePost(DeletePostByIdReqDTO requestParam) {
        Post post = getById(requestParam.getPostId());
        if (post == null) {
            return Result.error(404, "帖子不存在");
        }

        if (!post.getUserId().equals(LoginUserContextHolder.getUserId())) {
            return Result.error(403, "无权删除他人的帖子");
        }

        removeById(requestParam.getPostId());
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> unlikePost(UnLikePostReqDTO requestParam) {
        Integer userId = LoginUserContextHolder.getUserId();
        
        // 删除点赞记录
        LambdaQueryWrapper<PostLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostLike::getPostId, requestParam.getPostId())
                .eq(PostLike::getUserId, userId);
        if (postLikeMapper.delete(wrapper) == 0) {
            return Result.error(400, "未点赞过该帖子");
        }

        // 更新帖子点赞数
        Post post = getById(requestParam.getPostId());
        post.setPostSupport(post.getPostSupport() - 1);
        updateById(post);

        return Result.success();
    }

    @Override
    public List<GetPostListRespDTO> getPostList(GetPostListReqDTO requestParam) {
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        if (requestParam.getPostModel() != null) {
            wrapper.eq(Post::getPostModel, requestParam.getPostModel());
        }
        if (StringUtils.hasText(requestParam.getKeyword())) {
            wrapper.and(w -> w.like(Post::getPostTitle, requestParam.getKeyword())
                    .or()
                    .like(Post::getPostMsg, requestParam.getKeyword()));
        }
        wrapper.orderByDesc(Post::getPostTime);

        List<Post> posts = list(wrapper);
        Integer userId = LoginUserContextHolder.getUserId();

        return posts.stream().map(post -> {
            GetPostListRespDTO respDTO = new GetPostListRespDTO();
            BeanUtils.copyProperties(post, respDTO);

            // 检查是否点赞
            LambdaQueryWrapper<PostLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(PostLike::getPostId, post.getPostId())
                    .eq(PostLike::getUserId, userId);
            respDTO.setIsLike(postLikeMapper.selectCount(likeWrapper) > 0);

            return respDTO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<GetPostListRespDTO> getPostByUserId(Integer userId) {
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Post::getUserId, userId)
                .orderByDesc(Post::getPostTime);

        List<Post> posts = list(wrapper);
        Integer currentUserId = LoginUserContextHolder.getUserId();

        return posts.stream().map(post -> {
            GetPostListRespDTO respDTO = new GetPostListRespDTO();
            BeanUtils.copyProperties(post, respDTO);

            // 检查是否点赞
            LambdaQueryWrapper<PostLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(PostLike::getPostId, post.getPostId())
                    .eq(PostLike::getUserId, currentUserId);
            respDTO.setIsLike(postLikeMapper.selectCount(likeWrapper) > 0);

            return respDTO;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> report(ReportPostAndSayReqDTO requestParam) {
        if (requestParam.getPostId() != null) {
            Post post = getById(requestParam.getPostId());
            if (post == null) {
                return Result.error(404, "帖子不存在");
            }
            post.setPostStatus(1);
            updateById(post);
        }
        
        if (requestParam.getSayId() != null) {
            PostSay say = postSayMapper.selectById(requestParam.getSayId());
            if (say == null) {
                return Result.error(404, "评论不存在");
            }
            // TODO: 处理评论举报逻辑
        }
        
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateSay(UpdateSayReqDTO requestParam) {
        PostSay say = postSayMapper.selectById(requestParam.getSayId());
        if (say == null) {
            return Result.error(404, "评论不存在");
        }

        if (!say.getUserId().equals(LoginUserContextHolder.getUserId())) {
            return Result.error(403, "无权修改他人的评论");
        }

        say.setSayContent(requestParam.getSayContent());
        postSayMapper.updateById(say);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> deleteSay(DeletePostSayReqDTO requestParam) {
        PostSay say = postSayMapper.selectById(requestParam.getSayId());
        if (say == null) {
            return Result.error(404, "评论不存在");
        }

        if (!say.getUserId().equals(LoginUserContextHolder.getUserId())) {
            return Result.error(403, "无权删除他人的评论");
        }

        postSayMapper.deleteById(requestParam.getSayId());

        // 更新帖子评论数
        Post post = getById(say.getPostId());
        int commentCount = Integer.parseInt(post.getPostSay());
        post.setPostSay(String.valueOf(commentCount - 1));
        updateById(post);

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> likeSay(LikePostSayReqDTO requestParam) {
        Integer userId = LoginUserContextHolder.getUserId();
        
        // 检查评论是否存在
        PostSay say = postSayMapper.selectById(requestParam.getSayId());
        if (say == null) {
            return Result.error(404, "评论不存在");
        }

        // 检查是否已点赞
        LambdaQueryWrapper<SayLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SayLike::getSayId, requestParam.getSayId())
                .eq(SayLike::getUserId, userId);
        if (sayLikeMapper.selectCount(wrapper) > 0) {
            return Result.error(400, "已经点赞过了");
        }

        // 添加点赞记录
        SayLike sayLike = new SayLike();
        sayLike.setSayId(requestParam.getSayId());
        sayLike.setUserId(userId);
        sayLike.setLikeTime(LocalDateTime.now());
        sayLikeMapper.insert(sayLike);

        // 更新评论点赞数
        say.setSaySupport(say.getSaySupport() + 1);
        postSayMapper.updateById(say);

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> unlikeSay(UnLikePostSayReqDTO requestParam) {
        Integer userId = LoginUserContextHolder.getUserId();
        
        // 检查评论是否存在
        PostSay say = postSayMapper.selectById(requestParam.getSayId());
        if (say == null) {
            return Result.error(404, "评论不存在");
        }

        // 删除点赞记录
        LambdaQueryWrapper<SayLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SayLike::getSayId, requestParam.getSayId())
                .eq(SayLike::getUserId, userId);
        if (sayLikeMapper.delete(wrapper) == 0) {
            return Result.error(400, "未点赞过该评论");
        }

        // 更新评论点赞数
        say.setSaySupport(say.getSaySupport() - 1);
        postSayMapper.updateById(say);

        return Result.success();
    }
} 